package com.jibei.mendo.utils;

import android.content.Context;
import android.media.MediaScannerConnection;
import android.util.Log;

import org.json.JSONArray;
import org.json.JSONObject;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.FileWriter;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.ArrayList;
import java.util.List;

/**
 * Created by Administrator on 2017/2/22 0022.
 */

public class FileUtils {

    public static boolean moveConfigFile(Context context, int rId, String path) {
        try {
            File fileFif = new File(path);
            if (!fileFif.exists()) {
                fileFif.createNewFile();
                OutputStream output = new FileOutputStream(fileFif);
                InputStream input = context.getResources().openRawResource(rId);
                int length = input.available();
                byte[] bts = new byte[length];
                input.read(bts);
                output.write(bts);
                input.close();
                output.close();
            }
            return true;
        } catch (IOException e) {
            e.printStackTrace();
            Log.d("lhl", "算法库配置文件创建失败file:" + path);
            return false;
        }
    }

    public static boolean moveOrCoverConfigFile(Context context, int rId, String path) {
        try {
            File fileFif = new File(path);
            if (fileFif.exists()) {
                fileFif.delete();
            }
            if (!fileFif.exists()) {
                fileFif.createNewFile();
            }
            OutputStream output = new FileOutputStream(fileFif);
            InputStream input = context.getResources().openRawResource(rId);
            int length = input.available();
            byte[] bts = new byte[length];
            input.read(bts);
            output.write(bts);
            input.close();
            output.close();
            return true;
        } catch (IOException e) {
            e.printStackTrace();
            Log.d("lhl", "算法库配置文件创建失败file:" + path);
            return false;
        }
    }

    /**
     * 获取文件夹大小
     *
     * @param file File实例
     * @return long
     */
    public static long getFolderSize(File file) {
        long size = 0;
        try {
            File[] fileList = file.listFiles();
            for (int i = 0; i < fileList.length; i++) {
                if (fileList[i].isDirectory()) {
                    size = size + getFolderSize(fileList[i]);

                } else {
                    size = size + fileList[i].length();

                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        //return size/1048576;
        return size;
    }


    /**
     * 删除单个文件
     *
     * @param filePath 被删除文件的文件名
     * @return 文件删除成功返回true，否则返回false
     */
    public static boolean deleteFile(String filePath) {
        try {
            if (filePath != null) {
                File file = new File(filePath);
                if (file.isFile() && file.exists()) {
                    return file.delete();
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return false;
    }

    /**
     * 删除文件夹以及目录下的文件
     *
     * @param filePath 被删除目录的文件路径
     * @return 目录删除成功返回true，否则返回false
     */
    public static boolean deleteDirectory(String filePath) {
        boolean flag = false;
        //如果filePath不以文件分隔符结尾，自动添加文件分隔符
        if (!filePath.endsWith(File.separator)) {
            filePath = filePath + File.separator;
        }
        File dirFile = new File(filePath);
        if (!dirFile.exists() || !dirFile.isDirectory()) {
            return false;
        }
        flag = true;
        File[] files = dirFile.listFiles();
        //遍历删除文件夹下的所有文件(包括子目录)
        for (int i = 0; i < files.length; i++) {
            if (files[i].isFile()) {
                //删除子文件
                flag = deleteFile(files[i].getAbsolutePath());
                if (!flag)
                    break;
            } else {
                //删除子目录
                flag = deleteDirectory(files[i].getAbsolutePath());
                if (!flag)
                    break;
            }
        }
        if (!flag)
            return false;
        //删除当前空目录
        return dirFile.delete();
    }

    /**
     * @param fromFile 被复制的文件
     * @param toFile   复制的目录文件
     * @param rewrite  是否重新创建文件
     */
    public static boolean copyFile(File fromFile, File toFile, Boolean rewrite) {
        if (!fromFile.exists() || !fromFile.isFile() || !fromFile.canRead()) {
            return false;
        }
        if (!toFile.getParentFile().exists()) {
            toFile.getParentFile().mkdirs();
        }
        if (toFile.exists() && rewrite) {
            toFile.delete();
        }

        FileInputStream fosfrom = null;
        FileOutputStream fosto = null;
        try {
            fosfrom = new FileInputStream(fromFile);
            fosto = new FileOutputStream(toFile);

            byte[] bt = new byte[1024];
            int c;
            while ((c = fosfrom.read(bt)) > 0) {
                fosto.write(bt, 0, c);
            }
        } catch (IOException e) {
            e.printStackTrace();
            return false;
        } finally {
            //关闭输入、输出流
            try {
                if (fosfrom != null) {
                    fosfrom.close();
                }
                if (fosto != null) {
                    fosto.flush();
                    fosto.close();
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return true;

    }

    /**
     * @param fromFilePath   被复制的文件路径
     * @param targetFilePath 目标文件路径
     * @param rewrite        是否重新创建文件
     */
    public static boolean copyFile(String fromFilePath, String targetFilePath, Boolean rewrite) {
        if (null == fromFilePath || null == targetFilePath) {
            return false;
        }
        return copyFile(new File(fromFilePath), new File(targetFilePath), rewrite);
    }

    //删除文件后, 通知媒体库更新文件夹
    public static void updateFileToSystem(Context context, String[] fileNames, MediaScannerConnection.OnScanCompletedListener listener) {
        MediaScannerConnection.scanFile(context, fileNames, null, listener);
    }

    /**
     * 写入内容到指定文件，可追加
     *
     * @param content          要写入的内容
     * @param fileAbsolutePath 文件绝对路径
     * @param append           是否追加至文件末尾
     */
    public static void writeToFile(String content, String fileAbsolutePath, Boolean append) {
        try {
            File file = new File(fileAbsolutePath);
            if (!file.exists()) {
                file.createNewFile();
            }
            FileWriter writer = new FileWriter(file, append);
            writer.write(content);
            writer.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    /**
     * 获取指定目录内所有文件路径
     *
     * @param dirPath 需要查询的文件目录
     * @param _type   查询类型，比如mp3什么的
     */
    public static JSONArray getAllFiles(String dirPath, String _type) {
        File f = new File(dirPath);
        if (!f.exists()) {//判断路径是否存在
            return null;
        }

        File[] files = f.listFiles();

        if (files == null) {//判断权限
            return null;
        }

        JSONArray fileList = new JSONArray();
        for (File _file : files) { //遍历目录
            if (_file.isFile() && _file.getName().endsWith(_type)) {
                String _name = _file.getName();
                String filePath = _file.getAbsolutePath();//获取文件路径
                String fileName = _file.getName().substring(0, _name.length() - 4);//获取文件名
                Log.i("lhl", "fileName:" + fileName);
                Log.i("lhl", "filePath:" + filePath);
                try {
                    JSONObject _fInfo = new JSONObject();
                    _fInfo.put("name", fileName);
                    _fInfo.put("path", filePath);
                    fileList.put(_fInfo);
                } catch (Exception e) {
                    Log.e("lhl", "遍历excel文件夹异常！");
                    e.printStackTrace();
                }
            } else if (_file.isDirectory()) {//查询子目录
                getAllFiles(_file.getAbsolutePath(), _type);
            } else {
                Log.e("lhl", "非xlsx文件！");
            }
        }
        return fileList;
    }

    public static boolean createDirectoryIfNotExist(String path) {
        File file = new File(path);
        if (!file.exists()) {
            return file.mkdir();
        }
        return false;
    }

    public static void createDirectoryIfNotExist(List<String> paths) {
        for (String path : paths) {
            boolean bb = createDirectoryIfNotExist(path);
        }
    }

    public static List<String> getFolderFilesName(File folder) {
        if (null == folder || !folder.exists() || folder.isFile()) {
            return new ArrayList<>();
        } else {
            List<String> list = new ArrayList<>();
            for (File file : folder.listFiles()) {
                list.add(file.getAbsolutePath());
            }
            return list;
        }
    }
}
